<?php
    $d_id = $_REQUEST["d_id"];
    $con=mysqli_connect("localhost","root","","hhuy");
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }
    
    $d = mysqli_query($con,"SELECT * FROM english_dialogue WHERE id = 1");
    $d_r = mysqli_fetch_array($d);
    
    $d_a = mysqli_query($con,"SELECT * FROM english_dialogue_answer WHERE dialogue_id = $d_id");
    //push answer
    $d_a_obj = array();
    while($d_a_row = mysqli_fetch_array($d_a))
    {
        $d_a_obj[$d_a_row['position']]['answer'] = $d_a_row['answer'];
        $d_a_obj[$d_a_row['position']]['result'] = $d_a_row['result'];
        $d_a_obj[$d_a_row['position']]['is_right'] = $d_a_row['is_right'];
    }
        
    
    //replace word
    $key_word   = '{word}';
    $key_word_dot   = ' ............ ';
    $arr_d_w = explode($key_word,$d_r['dialogue_word']);
    $dialogue_word = '';
    for($key=0; $key< count($arr_d_w); $key++)
    {
        $value = $arr_d_w[$key];
        if (isset($d_a_obj[$key+1]))
        {
            if ($d_a_obj[$key+1]['answer'] == "")
                $dialogue_word .= $value. "(". ($key+1 ).") ".$key_word_dot;    
            else
                
                $dialogue_word .=  $value. " ...<b style='color:blue;'> (". ($key+1 ).") " . $d_a_obj[$key+1]['answer'] . "</b>... ";            
        }
        else
        {
            if ($key == count($arr_d_w)-1)
                $dialogue_word .= $value;
            else
                $dialogue_word .= $value. "(". ($key+1 ).") ".$key_word_dot;    
        }
    }
    
    mysqli_close($con);
    $rep = array();
    $rep['dialogue'] = $dialogue_word;
    $rep['result'] = false;
    echo json_encode($rep);
?>
